//
// Created by china on 25-1-5.
//

#include "UserModel.h"

bool UserModel::insert(MySQLTable::User &user) {
    LOG_INFO<<"UserModel::insert";

    char sql[512];
    std::sprintf(sql, "INSERT INTO user(name,password,state) values('%s','%s','%s')", \
                                    user.name.c_str(), user.password.c_str(), user.state.c_str());

    auto pool = Pool::getInstance();
    auto conn = pool->getFreeConn();
    if(conn->update(sql)){
        user.id = mysql_insert_id(conn->getConn());
        return true;
    }
    return false;
}

struct MySQLTable::User UserModel::query(int id) {
    LOG_INFO<<"UserModel::query";
    struct MySQLTable::User user;
    char sql[512];  // 或者适合你长度的 buffer
    std::sprintf(sql, "SELECT * FROM user WHERE id = %d ", id);

    auto pool = Pool::getInstance();
    auto conn = pool->getFreeConn();
    MYSQL_RES* queryRes = conn->query(sql);
    if(queryRes != nullptr){
        MYSQL_ROW row = mysql_fetch_row(queryRes);
        if(row != nullptr){
            user.id = atoi(row[0]);
            user.name = row[1];
            user.password = row[2];
            user.state = row[3];
        }
    }
    //释放资源
    mysql_free_result(queryRes);
    return user;
}

bool UserModel::updateState(const MySQLTable::User &user) {
    LOG_INFO<<"UserModel::updateState";
    char sql[512];  // 或者适合你长度的 buffer
    std::sprintf(sql, "UPDATE user SET state='%s' WHERE id=%d ",user.state.c_str(),user.id);
    auto pool = Pool::getInstance();
    auto conn = pool->getFreeConn();
    if(conn->update(sql)){
        return true;
    }
    return false;
}

bool UserModel::resetUserState() {
    LOG_INFO<<"UserModel::resetUserState";
    std::string sql = "UPDATE user SET state = 'offline'";

    auto pool = Pool::getInstance();
    auto conn = pool->getFreeConn();
    if(conn->update(sql)){
        return true;
    }
    return true;
}
